/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.extension.filter;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.ICafSessionService;
import io.iec.edp.caf.rpc.api.annotation.RpcServerInterceptor;
import io.iec.edp.caf.rpc.api.filter.RpcServerFilter;
import io.iec.edp.caf.rpc.api.support.ConstanceVarible;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;

/**
 * RPC2.0的Session过滤器
 */
@Slf4j
@RpcServerInterceptor
public class SessionRpcServerFilter implements RpcServerFilter {

    @Override
    public void doInFilter(Map<String, Object> reqContext) {
        //请求开始 还原session
        String sessionId = (String) reqContext.get(ConstanceVarible.SESSION_ID);
        //认证失败
        if(sessionId==null){
            throw new SecurityException("gRPC 401 Unauthorized. There's no session information.");
        }
        ICafSessionService css = SpringBeanUtils.getBean(ICafSessionService.class);
        CafSession cafSession = css.findById(sessionId);
        if(cafSession==null || css.isExpired(sessionId)){
            throw new SecurityException("gRPC 401 Unauthorized. Can't recognize session information.");
        }
        if(log.isInfoEnabled()){
            log.info("gRPC set sessionId: "+sessionId);
        }
        //restore to security context
        SecurityContextHolder.getContext().setAuthentication(cafSession);

    }

    @Override
    public void doOutFilter(Map<String, Object> repContext) {
        //请求结束 清理上下文
        SecurityContextHolder.clearContext();
    }

    @Override
    public void doFilter(Map<String, Object> reqContext, Map<String, Object> repContext) {

    }
}
